import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/screens/attr_name/attr_management_page.dart';
import 'package:merchants/screens/category/list_page.dart';
import 'package:merchants/screens/login_screen.dart';
import 'package:merchants/screens/main_tab_screen.dart';
import 'package:merchants/screens/merchant/merchant_create_screen.dart';
import 'package:merchants/screens/merchant/merchant_edit_screen.dart';
import 'package:merchants/screens/merchant/merchant_pending_screen.dart';
import 'package:merchants/screens/my/merchant_user_screen.dart';
import 'package:merchants/screens/my/my_default_screen.dart';
import 'package:merchants/screens/my/role_management_screen.dart';
import 'package:merchants/screens/orders/list_screen.dart';
import 'package:merchants/screens/spu/spu_form_page.dart';
import 'package:merchants/screens/spu/spu_list_page.dart';
// import 'package:merchants/screens/category/test_data_page.dart';
import 'package:merchants/services/app.dart';
import 'package:merchants/utils/push-manager.dart';
import 'package:merchants/utils/we-chat-manager.dart';
import 'package:merchants/widgets/terms_agreement_dialog.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:merchants/screens/merchant/profile_fill_screen.dart';
import 'package:merchants/providers/settings_provider.dart';
import 'package:merchants/providers/agreement_provider.dart';
import 'dart:io';

/// ---------------------------
/// 入口函数：负责所有一次性初始化
/// ---------------------------
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

   await SharedPreferences.getInstance();

  // 开发环境禁用SSL证书验证
  if (kDebugMode) {
    HttpOverrides.global = _MyHttpOverrides();
  }

  // 创建一个全局 ProviderContainer，供所有 SDK 使用
  final container = ProviderContainer();

  // 确保 Settings 已加载完成（含 baseUrl）
  try {
    await container.read(settingsProvider.notifier).loaded;
  } catch (e) {
    if (kDebugMode) print('Settings 加载失败: $e');
  }

  // 初始化 AppServices
  await AppServices.initialize();

  try {
    await WeChatManager.init(container);
    await PushManager.init(container);
  } catch (e) {
    if (kDebugMode) {
      print('初始化失败: $e');
    }
  }

  runApp(
    // 使用 UncontrolledProviderScope 将已经初始化好的 container 注入到整个应用
    UncontrolledProviderScope(
      container: container,
      child: const MyApp(),
    ),
  );
}

// 开发环境禁用SSL证书验证
class _MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback = (cert, host, port) => true;
  }
}

final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp.router(
      routerConfig: _router,
      title: '多赚薅省',
      theme: ThemeData(primarySwatch: Colors.green),
      scaffoldMessengerKey: PushManager.scaffoldMessengerKey,
      builder: (context, child) {
        if (child == null) {
          return const _LoadingScreen();
        }
        
        // 使用响应式协议状态检查
        return Consumer(
          builder: (context, ref, child) {
            final agreementStatusAsync = ref.watch(agreementCheckProvider);
            
            return agreementStatusAsync.when(
              data: (hasAgreed) {
                // 如果已同意协议，直接显示应用内容
                if (hasAgreed) {
                  return child!;
                }
                
                // 如果未同意协议，显示协议对话框
                return _AgreementCheckScreen(child: child!);
              },
              loading: () => const _LoadingScreen(),
              error: (error, stack) {
                print('协议检查失败: $error');
                // 错误时默认显示协议对话框
                return _AgreementCheckScreen(child: child!);
              },
            );
          },
          child: child,
        );
      },
    );
  }

  Future<void> _initializeApp() async {
    // 预留给其他耗时但不依赖 SDK 的初始化任务
    await Future.delayed(Duration.zero);
  }
}

// 协议检查屏幕
class _AgreementCheckScreen extends ConsumerStatefulWidget {
  final Widget child;

  const _AgreementCheckScreen({required this.child});

  @override
  ConsumerState<_AgreementCheckScreen> createState() => _AgreementCheckScreenState();
}

class _AgreementCheckScreenState extends ConsumerState<_AgreementCheckScreen> {
  bool _dialogShown = false;

  @override
  void initState() {
    super.initState();
    // 延迟显示对话框，确保上下文已准备好
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_dialogShown && mounted) {
        _showAgreementDialog();
      }
    });
  }

  void _showAgreementDialog() {
    if (_dialogShown) return;
    _dialogShown = true;

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => TermsAgreementDialog(
        onAgreed: () async {
          // 使用响应式状态管理器设置同意状态
          await ref.read(agreementStatusProvider.notifier).setAgreed(true);
          Navigator.of(ctx).pop();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 显示应用内容，但协议对话框会覆盖在上面
    return widget.child;
  }
}

class _LoadingScreen extends StatelessWidget {
  const _LoadingScreen();

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 20),
            Text('正在初始化...'),
          ],
        ),
      ),
    );
  }
}

/// ---------------------------
/// 路由配置
/// ---------------------------
final GoRouter _router = GoRouter(
  initialLocation: '/login',
  navigatorKey: _navigatorKey,
  routes: [
    GoRoute(path: '/', redirect: (context, state) => '/tabs'),
    GoRoute(path: '/login', builder: (context, state) => const LoginScreen()),
    GoRoute(
      path: '/merchant',
      redirect: (context,state)=> '/merchant/pending',
      routes: [
        GoRoute(
          path: 'create',
          builder: (context, state) => const MerchantCreateScreen(),
        ),
        GoRoute(
          path: 'edit/:merchantId',
          builder: (context, state) {
            final merchantId = state.pathParameters['merchantId']!;
            return MerchantEditScreen(merchantId: merchantId);
          },
        ),
        GoRoute(
          path: 'pending',
          builder: (context, state) => const MerchantPendingScreen(),
        ),
      ],
    ),
    GoRoute(
      path: '/tabs',
      builder: (context, state) => const MainTabPage(),
      routes: [
        GoRoute(
          path: 'spu',
          redirect: (context, state) {
            // 只有当完全匹配 /tabs/spu 时才重定向到 list
            if (state.uri.path == '/tabs/spu') {
              return '/tabs/spu/list';
            }
            return null;
          },
          routes: [
            GoRoute(
              path: 'list',
              builder: (context, state) => const SpuListPage(),
            ),
            GoRoute(
              path: 'create',
              builder: (context, state) => const SpuFormPage(spuId: null),
            ),

            GoRoute(
              path: 'form/:spuId',
              builder: (context, state) {
                final spuId = state.pathParameters['spuId'];
                return SpuFormPage(spuId: spuId);
              },
            ),
          ],
        ),
        GoRoute(
          path: 'category',
          builder: (context, state) => const CategoryListPage(),
          routes: [
            // GoRoute(
            //   path: 'test',
            //   builder: (context, state) => const CategoryTestDataPage(),
            // ),
          ],
        ),
        GoRoute(
          path: 'attr-name',
          builder: (context, state) => const AttrManagementPage(),
        ),
        GoRoute(
          path: 'orders',
          builder: (context, state) => const OrderDefaultScreen(),
        ),
        GoRoute(
          path: 'my',
          builder: (context, state) => const MyDefaultScreen(),
          routes: [
            GoRoute(
              path: 'merchant-user-management',
              builder: (context, state) => const MerchantUserManagementScreen(),
            ),
            GoRoute(
              path: 'profile-fill',
              builder: (context, state) => const ProfileFillScreen(),
            ),
            GoRoute(
              path: 'role-management',
              builder: (context, state) => const RoleManagementScreen(),
            ),
          ],
        ),
      ],
    ),
  ],
);
